package com.channel.modules.security.service;

import cn.hutool.core.util.RandomUtil;
import com.channel.modules.security.config.bean.LoginProperties;
import com.channel.modules.security.service.dto.JwtUserDto;
import com.commons.utils.RedisUtils;
import com.commons.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class UserCacheManager {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${login.user-cache.idle-time}")
    private Long idleTime;

    /**
     * 返回用户缓存
     */
    public JwtUserDto getUserCache(String userName){
        if(StringUtils.isNoneEmpty(userName)){
            Object obj = redisUtils.get(LoginProperties.cacheKey + userName);
            if(obj!=null){
                return (JwtUserDto) obj;
            }
        }
        return null;
    }

    /**
     * 添加到缓存redis
     */
    @Async
    public void addUserCache(String userName,JwtUserDto user){
        if(StringUtils.isNotEmpty(userName)){
            //添加数据，避免数据同时过期
            long time=idleTime+ RandomUtil.randomInt(900,1800);
            redisUtils.set(LoginProperties.cacheKey+userName,user,time);
        }
    }

    /**
     * 清理用户缓存信息
     */

    @Async
    public void cleanUserCache(String userName){
        if(StringUtils.isNotEmpty(userName)){
            redisUtils.del(LoginProperties.cacheKey+userName);
        }
    }
}
